<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="__ROOT__/Public/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
	var $personTable;
	//通过id 删除person
	function deletePerson(id){
		$.ajax({
			url:'__ROOT__/index.php/Home/Person/deleteById',
			type:'post',
			data:{
				id:id
			},
			success:function(data){
				if(data=='success'){
					//删除成功 刷新表格
					initPersonTable();
				}else{
					alert('删除失败!');
				}
			},
			error:function(){
				alert('删除失败!');
			}		
		});
	}
	//初始化person table
	function initPersonTable(){
		$personTable.empty();
		$.ajax({
			url:'__ROOT__/index.php/Home/Person/findAllPerson',
			success:function(data){
				//成功获取person
				for(var i=0;i<data.length;i++){
					var person = data[i];
					var $tr = $("<tr><td>"+person.name+"</td><td>"
							+person.age+"</td><td>"+person.gender+"</td><td>"
							+person.address+"</td><td><button onclick='deletePerson("
									+person.id+")'>delete</button></td></tr>");
					//添加到表格
					$tr.appendTo($personTable);
				}
			}		
		});
	}

	function addPerson(){
		var person = {};
		person.name = $('#personName').val();
		person.age = $('#personAge').val();
		person.address = $('#personAddress').val();
		person.gender = $('#personGender').val();

		$.ajax({
			type:'POST',
			url:'__ROOT__/index.php/Home/Person/insertPerson',
			data:{
				name:person.name,
				age:person.age,
				address:person.address,
				gender:person.gender,
			},
			success:function(data){
				if(data=='success'){
					//更新表格
					initPersonTable();
				}else{
					alert('添加person失败');
				}
			},
			error:function(){
				alert('添加person失败');
			}
		});
	}
	
	$(function(){
		$personTable = $('#personTable');
		initPersonTable();
	});
</script>
</head>
<body>
<table id="personTable">
	
</table>
<h2>添加person</h2>
<form>
	<table>
		<tr>
			<td>
				name
			</td>
			<td>
				<input id="personName" name="name" type="text"/>
			</td>
		</tr>
		<tr>
			<td>
				age
			</td>
			<td>
				<input id="personAge" name="age" type="number"/>
			</td>
		</tr>
		<tr>
			<td>
				gender
			</td>
			<td>
				<input id="personGender" name="gender" type="text"/>
			</td>
		</tr>
		<tr>
			<td>
				address
			</td>
			<td>
				<input id="personAddress" name="address" type="text"/>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<button onclick="addPerson()">Add Person</button>
			</td>
		</tr>
	</table>
</form>

</body>
</html>